//
//  ZZLButton.swift
//  ZZLButton
//
//  Created by KDWL on 2023/1/9.
//

import UIKit

public enum ZZLButtonDirection {
    /// 水平 先图片后标题
    case horizontalImageTitle
    /// 水平 先标题后图片
    case horizontalTitleImage
    /// 垂直 先图片后标题
    case verticalImageTitle
    /// 垂直 先标题后图片
    case verticalTitleImage
}

open class ZZLButton: UIButton {
    /// 布局方向
    public var zl_direction: ZZLButtonDirection = .horizontalImageTitle
    /// 空隙
    public var zl_gap: CGFloat = 4.0
    /// 图片宽度
    public var zl_imageWidth: CGFloat { get { return self.imageView?.bounds.size.width ?? 0 } }
    /// 图片高度
    public var zl_imageHeight: CGFloat { get { return self.imageView?.bounds.size.height ?? 0 } }
    /// 标题宽度
    public var zl_titleWidth: CGFloat { get { return self.titleLabel?.bounds.size.width ?? 0 } }
    /// 标题高度
    public var zl_titleHeight: CGFloat { get { return self.titleLabel?.bounds.size.height ?? 0 } }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        switch self.zl_direction {
        case .horizontalImageTitle:
            self.horizontalImageTitle()
            break
        case .horizontalTitleImage:
            self.horizontalTitleImage()
            break
        case .verticalImageTitle:
            self.verticalImageTitle()
            break
        case .verticalTitleImage:
            self.verticalTitleImage()
            break
        }
    }
    /// 水平 先图片后标题
    func horizontalImageTitle() {
        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: zl_gap)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: zl_gap, bottom: 0, right: 0)
    }
    /// 水平 先标题后图片
    func horizontalTitleImage() {
        self.imageEdgeInsets = UIEdgeInsets(top: 0, left: zl_titleWidth + zl_gap, bottom: 0, right: -zl_titleWidth)
        self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -zl_imageWidth, bottom: 0, right: zl_imageWidth + zl_gap)
    }
    /// 垂直 先图片后标题
    func verticalImageTitle() {
        self.imageEdgeInsets = UIEdgeInsets(top: -zl_titleHeight - zl_gap, left: 0, bottom: 0, right: -zl_titleWidth)
        self.titleEdgeInsets = UIEdgeInsets(top: zl_imageHeight + zl_gap, left: -zl_imageWidth, bottom: 0, right: 0)
    }
    /// 垂直 先标题后图片
    func verticalTitleImage() {
        self.imageEdgeInsets = UIEdgeInsets(top: zl_titleHeight + zl_gap, left: 0, bottom: 0, right: -zl_titleWidth)
        self.titleEdgeInsets = UIEdgeInsets(top: -zl_imageHeight - zl_gap, left: -zl_imageWidth, bottom: 0, right: 0)
    }
}
